package com.example.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.BaseContext;
import com.example.demo.entity.*;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

@Autowired
    private ShoppingCartService shoppingCartService;
   @Autowired
    private OrderDetailService orderDetailService;
   @Autowired
    private AddressBookService addressBookService;
   @Autowired
    private UserService userService;

    /**
     * 用户下单
     *
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        Long userId = BaseContext.getCurrentId();

        //用工具类生成id 设置为订单号
        Long orderId = IdWorker.getId();//订单号
        orders.setNumber(String.valueOf(orderId));
        orders.setId(orderId);


        orders.setUserId(userId);
        //设置为待付款
        orders.setStatus(1);

        //设置为微信支付 和 支付时间 下单时间
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(1);
        orders.setCheckoutTime(LocalDateTime.now());
        //设置为待派送
        orders.setStatus(2);

        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        User user = userService.getById(userId);
        orders.setUserName(user.getName());
        //查询购物车内容
        LambdaQueryWrapper<ShoppingCart> shoppingCartQW = new LambdaQueryWrapper<>();
        shoppingCartQW.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartQW);

        //原子类整数 保证线程安全
        AtomicInteger amount = new AtomicInteger(0);
        //计算订单总额并将购物车中的数据放入订单详情
        for (ShoppingCart shoppingCart : shoppingCartList) {
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orderId);
            if (shoppingCart.getDishId() != null) {
                orderDetail.setDishId(shoppingCart.getDishId());
            } else {
                orderDetail.setSetmealId(shoppingCart.getSetmealId());
            }
            if (shoppingCart.getDishFlavor() != null) {
                orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            }
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(new BigDecimal((shoppingCart.getAmount().intValue() * shoppingCart.getNumber())));
            orderDetailService.save(orderDetail);

        }
        orders.setAmount(new BigDecimal(amount.get()));
        this.save(orders);
        //清空购物车
        shoppingCartService.delete();
    }
    //客户端点击再来一单
    /**
     * 前端点击再来一单是直接跳转到购物车的，所以为了避免数据有问题，再跳转之前我们需要把购物车的数据给清除
     * ①通过orderId获取订单明细
     * ②把订单明细的数据的数据塞到购物车表中，不过在此之前要先把购物车表中的数据给清除(清除的是当前登录用户的购物车表中的数据)，
     * 不然就会导致再来一单的数据有问题；
     * (这样可能会影响用户体验，但是对于外卖来说，用户体验的影响不是很大，电商项目就不能这么干了)
     */




    }

